package com.letoy.study.service.Impl;

import com.letoy.study.service.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;

import static com.letoy.study.utils.Constants.FAIL;
import static com.letoy.study.utils.Constants.SUCCESS;

@Service
public class MailServiceImpl implements MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;


    @Override
    public int sendHtmlMail(String to, String subject,
                            String content) {
        MimeMessage message = mailSender.createMimeMessage();
        int flag = FAIL;
        try {
            String mFrom = new String(("乐游工作室" + " <" + from + ">")
                    .getBytes(StandardCharsets.UTF_8));
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            flag = SUCCESS;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return flag;
    }



    @Override
    public int sendActivateCode(String email, String key) {
        return sendHtmlMail(email,
                "乐游实战平台登录激活码",
                "<html>您好,<br>" +
                        "<br>" +
                        "欢迎注册乐游实战平台，<br>" +
                        "<br>" +
                        "请在十分钟内激活您的账号，验证码为：<br>" +
                        "<br>" +
                        "<h3>" + key + "</h3>" +
                        "<br>" +
                        "如非您本人注册，则请忽略本邮件。<br>" +
                        "<br>" +
                        "乐游工作室<br>");
    }


}